package com.hc.demo_api820.service;

import com.hc.demo_api820.domain.Hospital;
import com.hc.demo_api820.domain.Orders;
import com.hc.demo_api820.domain.Setmeal;
import com.hc.demo_api820.dto.ResultResponse;
import com.hc.demo_api820.exception.TijianException;
import com.hc.demo_api820.exception.TijianExceptionEnum;
import com.hc.demo_api820.mapper.HospitalMapper;
import com.hc.demo_api820.mapper.OrdersMapper;
import com.hc.demo_api820.mapper.SetmealMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    OrdersMapper ordersMapper;
    @Autowired
    HospitalMapper hospitalMapper;
    @Autowired
    SetmealMapper setmealMapper;
    /**
     * 创建订单的方法
    * */
    @Override
    @Transactional  //开启事务注解，确保整个操作符合事务的四个特征：原子性，一致性，持久性，隔离性
    public ResultResponse careateOrders(Orders orders){
        ResultResponse resultResponse = null;

        /**
         * 算法：
         * 1.检查该用户当天没有重复预约 Orders表与当前用户有关的数据锁住， select * from orders where userId=? and ordersDate=?
         * 2.检查医院有没有余号 获取医院的当天的总号数-已经预约的号数=余号数量
         * 3.调用Mapper往数据库插入一条订单数据
         * */
        //1.检查该用户当天没有重复预约
        List<Orders> ordersList = ordersMapper.selectByUserIdAndOrdersDate(orders);
        if(ordersList!= null&&ordersList.size()>0){
            throw new TijianException(TijianExceptionEnum.ALREADY_APPOINTMENT.getEnCode(), TijianExceptionEnum.ALREADY_APPOINTMENT.getEnMessage());
        }
        //2.检查医院有没有余号 获取医院的当天的总号数-已经预约的号数=余号数量
        if (!haveRemainderNumber(orders)) {
            throw new TijianException(TijianExceptionEnum.NOT_HAVE_REMAINOER_MUMBER.getEnCode(), TijianExceptionEnum.NOT_HAVE_REMAINOER_MUMBER.getEnMessage());
        }

        //3.往数据库插入一条订单数据
        ordersMapper.insertOrder(orders);
        resultResponse = new ResultResponse(ResultResponse.SUCCESS_CODE,ResultResponse.SUCCESS_DESC);
        return resultResponse;
    }

    @Override
    public ResultResponse queryOrderByUserId(String userId) {
        //1.查询用户的订单
        List<Orders> ordersList = ordersMapper.selectByUserId(userId);
        //2.这个for循环帮助每个订单 获取 对于套餐数据
        for (Orders o:ordersList) {
            Integer smId = o.getSmId();

            //拿着套餐编号去查询套餐表，这样能获取套餐信息
            Setmeal setmeal = setmealMapper.selectByPrimaryKey(smId);

            o.setSetmeal(setmeal);
        }
        return new ResultResponse(ResultResponse.SUCCESS_CODE,ResultResponse.SUCCESS_DESC,ordersList);
    }

    @Override
    public ResultResponse cancelAppointment(Integer orderId) {
        ordersMapper.deleteByPrimaryKey(orderId);
        return new  ResultResponse(ResultResponse.SUCCESS_CODE,ResultResponse.SUCCESS_DESC,null);
    }

    /**
     * 检查医院某天有没有余号
     * 有：返回true
     * 没有：返回false
     */
    public Boolean haveRemainderNumber(Orders orders){   //2025-09-02 周二
        Boolean result = false;
        //1.获取医院当天的总号数            -已经预约的号数=余号数量
        //先获取rule
        Hospital hospital=hospitalMapper.selectByPrimaryKey(orders.getHpId());
        String rule = hospital.getRule();   //"0,200,200,200,200,200,100"=>[0,200,200,200,200,200,100]
        //根据orderDate获取当天的总号数；
        //date --周几  数字1==周一，7==周日
        int dayOfWeek = getWeekDayNumber(orders.getOrderDate());
        int totalNumber = Integer.parseInt(rule.split(",")[dayOfWeek]);   //索引2 去数组中索引是2的值 为200
        //2.已经预约的号数
        int appointmentNumber = ordersMapper.selectAlreadyAppointmentNoumber(orders);
        //3.余号数量
        int remainderNumber = totalNumber - appointmentNumber;
        return remainderNumber>0?true:false;
    }

    /**
     * 获取日期的星期几（数字：1=周一，7=周日）
     * */
    public static int getWeekDayNumber( Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        return dayOfWeek == 1?7:dayOfWeek-1;
    }
}
